<template>
<div>
  <!-- 按钮 -->
  	<div v-on:click="showMenu"   :style="style" :class="cls">
    	<div class="weui-uploader__input-box"></div>
  	</div>
	<!-- 内容 -->
	<div class="weui-uploader__bd" style="display: inline-block;" v-if="fileList.length>0">
		<ul class="weui-uploader__files">
			<li class="weui-uploader__file" v-for="file in fileList"  style="text-align: right;">
				<img :src="file.url" @click="clickImg(file)" :style="{height:'100%',width:'100%'}"/>
				<x-icon  style="position:relative;fill: rgb(255, 0, 0);top:-58px" type="ios-close-outline"
					size="20" @click="del(file)" class="icon-red"></x-icon>
				 <!-- <x-button plain mini style="position:relative;width:79px;height:24px;border-radius: 0;line-height: 26px;border-color: #eee;color: #9c9c9c;"
          			:style="{top:file.type=='file'||permission=='r'?'-8px':'-33px'}"
          			type="primary" @click.native="download(file)">
          			{{file.newFileName}}
        		</x-button> -->
				<a :id="file.id" :href="file.url" download></a>
			</li>
		</ul>
	</div>

	<!-- 上传进度 -->
	<loading :show="uploadingFile.active" :text="uploadingFile.statusText"></loading>

	<!-- 选择方式菜单 -->
	<actionsheet v-model="show" :menus="menus" @on-click-menu="click" show-cancel></actionsheet>

	<!-- 上传附件组件 -->
	<file-upload ref="upload" name="file" :input-id="fileUploadId"
		:extensions="extensions" :accept="accept" capture="camera"
		v-model="files" :custom-action="customAction" :multiple="multiple"
		@input-file="inputFile" @input-filter="inputFilter">
	</file-upload>

	<!-- 预览图片 -->
	<x-dialog v-model="showImg" hide-on-blur>
		<div class="img-box">
        	<img :src="showImgUrl" style="max-width:100%;"/>
        </div>
	</x-dialog>
</div>
</template>

<script>

import Vue from 'vue';
const VueUploadComponent = require('vue-upload-component');
Vue.component('file-upload', VueUploadComponent);
import { Popup } from 'vux';
Vue.component('popup', Popup);
import { XButton } from 'vux';
Vue.component('x-button', XButton);
import { Group } from 'vux';
Vue.component('group', Group);
import { Flexbox, FlexboxItem } from 'vux';
Vue.component('flexbox', Flexbox);
Vue.component('flexbox-item', FlexboxItem);
import { XImg } from 'vux';
Vue.component('x-img', XImg);
import { Actionsheet } from 'vux';
Vue.component('actionsheet', Actionsheet);
import { Loading } from 'vux';
Vue.component('loading', Loading);
import common from '@/components/customize/plugins/common.js'
/**
 * <ab-upload v-model="files" :permission="xxx">
 * 	  <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary fa fa-upload">上传</a>
 * </ab-upload>
 */
export default {
	props:{
		value : {
			default : "[]"
		},
    multiple: {
      type: Boolean,
      default: false
    },
		permission : {},
		extensions : {
			default : ""
		},
		accept : {
			default : ""
		},
    itemId: {
      type: String,
      default: ''
    },
    taskId: {
      type: String,
      default: ''
    },
		size : {}
	},
	data () {
		return {
			fileImgUrl : require("@/assets/file.png"),
		  	show : false,
		  	menus: {
			  	 photo: "拍照",
			  	 file: "选择文件"
	      	},
      	 	files:[],
          fileList:[],
		  	fileUploadId:"",
		  	url:Vue.__ctx +"/sys/sysFile/upload",
		  	style :{
	    		cursor :"pointer",
          display: 'inline-block'
	    	},
        	cls:"",
	    	showImg : false,
	    	showImgUrl : "",
	    	uploadingFile : {},
	  	}
	},
	mounted () {
		this.fileUploadId = "fileId"+Math.random();//随机id
		this.show = false;
		this.handleStyle()
    if (this.itemId) {
      this.getImageInfo()
    }
	},
	methods: {
		showMenu : function(){
			this.show = true;
		},
		click : function(key){
			if(key=="photo"){//拍照
				$(document.getElementById(this.fileUploadId)).attr("capture","camera");
				$(document.getElementById(this.fileUploadId)).attr("cameraDisable","false");
				$(document.getElementById(this.fileUploadId)).attr("accept","image/*");
			}
			if(key=="file"){//文件上传
				$(document.getElementById(this.fileUploadId)).removeAttr("capture");
				$(document.getElementById(this.fileUploadId)).removeAttr("cameraDisable");
				if(this.accept){
					$(document.getElementById(this.fileUploadId)).attr("accept",this.accept);
				}else{
					$(document.getElementById(this.fileUploadId)).removeAttr("accept");
				}
			}
			//手动发布事件
			var event = document.createEvent('MouseEvents')
		    event.initMouseEvent('click',false,false)
		    document.getElementById(this.fileUploadId).dispatchEvent(event)
		},
    /**
     * 上传图片
     */
    UploadImage: function(base64Strs) {
      return new Promise((resolve, reject) => {
        try {
          let base64Strings = base64Strs
          let upload = this.baseService.post(this.__ctx + '/image/upload/base64', base64Strings).then(res => {
            if (res.isOk) {
              resolve(res.data)
              Vue.tools.toast(res.msg)
              this.$nextTick(()=>{
                this.fileList.push(res.data[0])
              })
            } else {
              Vue.$vux.toast.show({
                text: res.msg + ' 上传失败！',
                type: 'text',
                time: 1500,
                position: 'middle'
              })
              reject(res)
            }
          }).catch(error => {
            reject(error)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
   /*
    获取图片反显信息
    */
     getImageInfo () {
       let params = {
         fileNumber: this.taskId,
         fileType: this.itemId
       }
       let upload = this.baseService.getParams(`${this.__ctx}/attachment/listAll`,params).then(res => {
         if (res.isOk) {
           this.fileList = res.data.map(item=>{
             return {
              url: item.fileAddress,
              newFileName: item.fileName,
              fileName: item.fileName,
              id: item.id,
              fileNumber: item.fileNumber,
              fileType: item.fileType
             }
           })
         }
       }).catch(error => {
       })
     },
		customAction : async function(file, component) {
      let data = await common.ImageCompress(file.file)
      let reader = new FileReader()
      reader.readAsDataURL(data)
      reader.onload = () => {
        let requestData = [{
          fileNumber: this.taskId,
          base64: reader.result,
          fileType: this.itemId
        }]
       this.UploadImage(requestData)
      }
		},
		//添加，更新，移除 后
		inputFile : function(newFile, oldFile) {
			// 自动上传
	      	if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
	        	if (!this.$refs.upload.active) {
	          		this.$refs.upload.active = true
	        	}
	      	}
      	 	// 更新文件
	      	if (newFile && oldFile) {
	      		this.uploadingFile = newFile
	      		// 开始上传
            	if (newFile.active && newFile.active !== oldFile.active) {
            		newFile.statusText = "开始上传"
	            }

	            // 上传进度
	            if (newFile.progress !== oldFile.progress) {
	            	newFile.statusText = "上传中..." + newFile.progress + "%"
	            }

	            // 上传错误
	            if (newFile.error !== oldFile.error) {
	            	newFile.statusText = "上传错误"
	            }

	            // 上传成功
	            if (newFile.success !== oldFile.success) {
	            	var result = newFile.response
	            	newFile.statusText = result.msg
	            }
	      	}

	     	// 删除文件
	      	if (!newFile && oldFile) {
          	}
		},
		inputFilter : function(newFile, oldFile, prevent) {
			if(this.extensions && !this.extensions.split(",").includes(newFile.name.split(".")[1])){
				Vue.tools.toast("仅支持文件类型：" + this.extensions);
				prevent();
				return
			}

			// 添加文件
			if (newFile && !oldFile) {
				if(this.size&&this.files&&this.files.length>=this.size){
					Vue.tools.toast("已达附件上传数量限制：" + this.size);
					prevent()
					return
				}
	    }
		},
		clickImg : function(file){
      		if(file.type=="file"){
        		return this.download(file)
      		}
		  	if (!/\.(jpeg|jpe|jpg|gif|png|webp|ico)$/i.test(file.newFileName)) {
				Vue.tools.toast("系统仅支持图片预览")
        		return;
	        }
			this.showImg = true
			if(file.url){
				this.showImgUrl = file.url
			}else{
				this.showImgUrl = file.src
			}
		},
		del : function(file) {
			var idx = this.fileList.indexOf(file)
			var that = this
        	var url = this.__ctx + '/attachment/remove/' + file.id;
        	var post = this.baseService.delete(url).then(res=>{
          if (res.isOk) {
            Vue.tools.toast("删除成功")
            this.$nextTick(()=>{
              that.fileList.splice(idx,1)
            })
          } else {
             Vue.tools.toast(res.msg)
          }
        })
		},
		download : function(file) {
			//Vue.tools.toast("若无法正常下载附件可在UC等专用浏览器下载（QQ/微信等APP内置浏览器的限制问题）");
			var fileFrame = document.createElement('iframe')
			fileFrame.src = file.url
			fileFrame.style.display = 'none'
			document.body.appendChild(fileFrame)
	    },
	    handleStyle : function(){
	    	if(!this.$vnode.context.$validity){
	    		this.$vnode.context.$validity = {}
	    	}
			if(this.permission == "b"){
 				if(!this.value||this.value=="[]"){
 					this.$vnode.context.$validity[this.$attrs.desc] = "必填"
 					this.cls = "file-valid-error"
 				}else{
 					delete this.$vnode.context.$validity[this.$attrs.desc]
 					this.style["border"]  = ""
        			this.cls = ""
 				}
 			}
			//处理值
			this.files = JSON.parse(this.value || "[]")
			var that = this
			this.files.forEach(function(file){
				file.success = true
				file.statusText = "已上传"
				file.href = Vue.__ctx + "/sys/sysFile/download?fileId=" + file.id
				if (/\.(jpeg|jpe|jpg|gif|png|webp|ico)$/i.test(file.name)) {
					file.src = file.href
          file.type = "img"
				}else{
					file.src = that.fileImgUrl
          file.type = "file"
				}
        	file.ext = file.name.split("\.")[1].toUpperCase()
			});
 		},
	},
 	watch : {
 		//数据更新时 在td 下增加按钮
		value : function(newVal,oldVal){
 			if (newVal != oldVal) {
 				this.handleStyle()
			}
 		},
 		files : {
			deep: true ,
			handler : function(newVal, oldVal) {
				var list = []
				this.files.forEach(function(file){
					if(!file.success){
						return
					}
					list.push({
						id : file.id,
						name : file.name
					})
				})
				this.$emit('input', JSON.stringify(list))
			}
 		}
 	},
 	destroyed :function (){
 		delete this.$vnode.context.$validity[this.$attrs.desc];
 	},
}
</script>

<style scoped lang="less">
  .weui-uploader__input-box {
    margin: 0;
    width: 50px;
    height: 50px;
  }
  .weui-uploader__files {
    overflow: hidden;
    .weui-uploader__file{
      width: 50px;
      height: 50px;
      margin: 5px 10px;
    }
  }
  /deep/ .vux-actionsheet {
    float: left;
  }
.fa-upload:before{
  margin-right: 5px;
}
.file-valid-error .weui-uploader__input-box{
  border: 1px solid red;
}
.file-valid-error .weui-uploader__input-box:before{
      color:red;
      background-color: red;
      width:1px;
}
.file-valid-error .weui-uploader__input-box:after{
      color:red;
      background-color: red;
      height:1px;
}
.file-valid-error .fa-upload{
  background-color: #fd9191;
}
.file-name-txt{
  display: block;
  text-align: center;
  margin-top: -27px;
  color: #070cff;
  width: 80px;
  z-index: 1;
  text-overflow: ellipsis;
  overflow-x: hidden;
  font-size: 14px;
  float: left;
}
</style>
